<template>
  <div class="green-env-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">绿化环境管理系统</h1>
	            <p class="sub-title">从绿植栽种到日常管护，每一条绿化信息都关乎环境品质，以专业管理培育生机，让家园四季常青</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 搜索区域 -->
    <el-row :gutter="20" class="search-row">
      <el-col :span="6">
        <el-select 
          v-model="searchForm.status" 
          placeholder="请选择处理状态" 
          style="width: 100%;"
          clearable
        >
          <el-option label="未处理" value="未处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
          <el-option label="已处理" value="已处理"></el-option>
        </el-select>
      </el-col>
      <!-- 新增：按种类查询 -->
      <el-col :span="6">
        <el-select 
          v-model="searchForm.maintenanceType" 
          placeholder="请选择维护类型" 
          style="width: 100%;"
          clearable
        >
          <el-option label="种植" value="种植"></el-option>
          <el-option label="修剪" value="修剪"></el-option>
          <el-option label="喷药" value="喷药"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="handleSearch"
          style="width: 100%;"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="success" 
          icon="el-icon-plus" 
          @click="openAddDialog"
          style="width: 100%;"
        >
          新增维护记录
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table 
      :data="sortedTableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%; margin-top: 15px;"
      height="450"
      :row-class-name="tableRowClassName"
    >
      <el-table-column 
        fixed 
        prop="id" 
        label="编号" 
        width="250" 
        align="center"
      ></el-table-column>
      <!-- 新增：按监控编号排序功能 -->
      <el-table-column 
        prop="pointId" 
        label="监控编号" 
        width="250" 
        align="center"
        sortable
        @sort-change="handleSortChange"
      ></el-table-column>
      <el-table-column 
        prop="maintenanceType" 
        label="维护类型" 
        width="250" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="status" 
        label="处理状态" 
        width="300" 
        align="center"
      >
        <template v-slot:default="scope">
          <el-select 
            v-model="scope.row.status" 
            @change="() => updateStatus(scope.row)"
            placeholder="请选择"
            style="width: 120px;"
          >
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        width="180" 
        fixed="right"
        align="center"
      >
        <template v-slot:default="scope">
          <el-button 
            type="danger" 
            size="mini" 
            icon="el-icon-delete" 
            @click="deleteRecord(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-row type="flex" justify="center" class="pagination-row">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,50]" 
        :page-size="pageSize" 
        :total="sortedTableData.length"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-row>

    <!-- 新增对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="新增绿化维护记录" 
      width="50%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="addRules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="监控编号" prop="pointId">
          <el-input v-model.number="addForm.pointId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="维护类型" prop="maintenanceType">
          <el-select v-model="addForm.maintenanceType" placeholder="请选择">
            <el-option label="种植" value="种植"></el-option>
            <el-option label="修剪" value="修剪"></el-option>
            <el-option label="喷药" value="喷药"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option label="未处理" value="未处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd">确认新增</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { post } from '@/utils/axios';

// 状态选项
const statusOptions = [
  { value: '未处理', label: '未处理' },
  { value: '处理中', label: '处理中' },
  { value: '已处理', label: '已处理' }
];

// 搜索表单 - 新增了维护类型查询条件
const searchForm = reactive({
  status: '',
  maintenanceType: ''  // 新增：维护类型查询条件
});

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const tableData = ref([]);

// 排序相关 - 新增
const sortField = ref('');
const sortOrder = ref('');

// 新增相关
const addDialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = reactive({
  pointId: null,
  maintenanceType: '',
  status: ''
});

// 新增表单验证规则
const addRules = reactive({
  pointId: [
    { required: true, message: '请输入监控编号', trigger: 'blur' },
    { type: 'number', message: '监控编号必须为数字', trigger: 'blur' }
  ],
  maintenanceType: [
    { required: true, message: '请选择维护类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ]
});

// 表格行样式
function tableRowClassName({ row }) {
  const statusMap = {
    '未处理': 'red-row',
    '处理中': 'yellow-row'
  };
  return statusMap[row.status] || '';
}

// 分页尺寸变化
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
}

// 分页页码变化
function handleCurrentChange(val) {
  currentPage.value = val;
}

// 排序变化处理 - 新增
function handleSortChange({ column, prop, order }) {
  sortField.value = prop;
  sortOrder.value = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '';
}

// 计算属性：处理排序后的数据 - 新增
const sortedTableData = computed(() => {
  if (!sortField.value || !sortOrder.value) {
    return tableData.value;
  }
  
  // 创建数据副本进行排序，避免修改原数组
  return [...tableData.value].sort((a, b) => {
    if (sortField.value === 'pointId') {
      return sortOrder.value === 'asc' 
        ? a.pointId - b.pointId 
        : b.pointId - a.pointId;
    }
    return 0;
  });
});

// 搜索功能 - 修改：添加维护类型查询条件
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' });
  // 传递状态和维护类型两个查询条件
  post('/sc/greenenv/byMaintenanceType', { 
    status: searchForm.status,
    maintenanceType: searchForm.maintenanceType
  }, (res) => {
    loading.close();
    if (res && res.status === 1) {
      tableData.value = res.data;
      ElMessage.success(`查询成功，共${res.data.length}条记录`);
    } else {
      tableData.value = [];
      ElMessage.warning(res?.msg || '未查询到数据');
    }
  }, (error) => {
    loading.close();
    ElMessage.error('搜索失败：' + (error.message || '网络异常'));
  });
}

// 更新状态
function updateStatus(row) {
  const loading = ElLoading.service({ text: '更新中...' });
  // 仅传递需要更新的字段
  const updateData = {
    id: row.id,
    status: row.status
  };
  post('/sc/greenenv/updateById', updateData, (res) => {
    loading.close();
    if (res && res.status === 1) {
      ElMessage.success('状态更新成功');
    } else {
      ElMessage.error(res?.msg || '更新失败');
      // 失败时回滚状态显示
      fetchTableData();
    }
  }, (error) => {
    loading.close();
    ElMessage.error('更新失败：' + (error.message || '网络异常'));
    fetchTableData();
  });
}

// 删除记录
function deleteRecord(row) {
  ElMessageBox.confirm(
    `确定要删除编号为【${row.id}】的维护记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const loading = ElLoading.service({ text: '删除中...' });
    post('/sc/greenenv/deleteById', { id: row.id }, (res) => {
      loading.close();
      if (res && res.status === 1) {
        ElMessage.success('删除成功');
        fetchTableData(); // 重新加载数据
      } else {
        ElMessage.error(res?.msg || '删除失败');
      }
    }, (error) => {
      loading.close();
      ElMessage.error('删除失败：' + (error.message || '网络异常'));
    });
  }).catch(() => {
    // 取消删除不做处理
  });
}

// 打开新增对话框
function openAddDialog() {
  // 重置表单
  addFormRef.value?.resetFields();
  addDialogVisible.value = true;
}

// 提交新增
function submitAdd() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;

    const loading = ElLoading.service({ text: '新增中...' });
    post('/sc/greenenv/add', addForm, (res) => {
      loading.close();
      if (res && res.status === 1) {
        ElMessage.success('新增成功');
        addDialogVisible.value = false;
        fetchTableData(); // 重新加载数据
      } else {
        ElMessage.error(res?.msg || '新增失败');
      }
    }, (error) => {
      loading.close();
      ElMessage.error('新增失败：' + (error.message || '网络异常'));
    });
  });
}

// 获取所有数据
function fetchTableData() {
  const loading = ElLoading.service({ text: '加载中...' });
  post('/sc/greenenv/getAll', {}, (res) => {
    loading.close();
    if (res && res.status === 1) {
      tableData.value = res.data;
    } else {
      tableData.value = [];
      ElMessage.error(res?.msg || '数据加载失败');
    }
  }, (error) => {
    loading.close();
    ElMessage.error('加载失败：' + (error.message || '网络异常'));
  });
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.green-env-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.search-row {
  margin-bottom: 10px;
}

.pagination-row {
  margin-top: 20px;
}

/* 状态行样式 */
::v-deep .el-table .red-row {
  background-color: #fff1f0;
}

::v-deep .el-table .yellow-row {
  background-color: #fffbe6;
}

/* 操作按钮样式 */
::v-deep .el-table .el-button--mini {
  margin-right: 5px;
}
</style>